package com.douma.graph;


import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;

public class Graph {

    public static void main(String[] args) {
        Node node1 = new Node(1);
        Node node2 = new Node(2);
        Node node3 = new Node(3);
        Node node4 = new Node(4);

        node1.nodes = Arrays.asList(node2, node3, node4);

        Node node5 = new Node(5);
        Node node6 = new Node(6);

        node2.nodes = Arrays.asList(node5, node6);

        node3.nodes = Arrays.asList(node6);

        new Graph().dfs(node1);
    }

    private Set<Node> visited = new HashSet<>();
    // 递归 - 前序遍历 - 深度优先遍历
    public void dfs(Node node) {

        if (node == null) return;

        System.out.println(node.val);
        visited.add(node);

        // 多次递归调用
        for (Node child : node.nodes) {
            if (!visited.contains(child)) dfs(child);
        }
    }

}
